<?php
/**
 * Created by PhpStorm.
 * User: david.li
 * Date: 17/1/18
 * Time: 15:23
 */

namespace App\Models\Traits;

trait FileCacheAble
{

    public static function bootFileCacheAble()
    {
        // 创建数据 创建静态文件
        static::created(function ($model) {
            if($model->status == 'publish'){
                $content = view_first([$model->slug, $model->template, $model->category->content_template], 'content', ['article' => $model], [], true);
                static::create_static_page(public_path().'/'.static::$directory, $model->slug.'.html', $content);
            }else{
                //文章未发布
            }
        });
        // 修改数据 刷新静态文件
        static::updated(function ($model) {
            if($model->status == 'publish'){
                $content = view_first([$model->slug, $model->template, $model->category->content_template], 'content', ['article' => $model], [], true);
                static::create_static_page(public_path().'/'.static::$directory, $model->slug.'.html', $content);
            }else{
                // 文章未发布
            }

        });
        // 删除数据 修改静态文件
        static::deleted(function ($model) {
            // 生成页面: 文件已经删除,或,未发布
            static::delete_static_page(public_path().'/'.static::$directory.'/'.$model->slug.'.html');
        });
    }

    /**
     * 返回缓存的目录
     * @return string
     */
    public static function getDirectories()
    {
        return static::$directory;
    }


    //生成静态页方法
    public static function create_static_page($path, $file_name, $content)
    {
        if (is_dir($path)) {
            $file_name = static::handle_file_name($path, $file_name);
            file_put_contents($file_name, $content);
            chmod($file_name, 0777);
        }
        return $content;
    }

    //删除静态页方法
    public static function delete_static_page($file)
    {
        if (is_file($file)) {
            unlink($file);
        }
    }

    //清空目录下所有静态页方法
    public static function delete_all_static_page($path)
    {
        $file_path = scandir($path);
        foreach ($file_path as $value) {
            if ($value != '.' && $value != '..') {
                static::delete_static_page(static::handle_file_name($path, $value));
            }
        }
    }

    //文件路径处理函数
    public static function handle_file_name($path, $file_name)
    {
        if (substr($path, -1, 1) == '/') {
            return $path . $file_name;
        } else {
            return $path . '/' . $file_name;
        }
    }


}